# Copyright (C) Nicola Bizzoca   2006/2007  <hannibal_smith@users.sourceforge.net>
# Copyright (C) Simone Economo   2006/2007  <ekoes@users.sourceforge.net>
# 
#    This file is part of Absynth-FTP.
#
#    Absynth-FTP is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 3 of the License, or
#    (at your option) any later version.
#
#    Absynth-FTP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import gtk
import sys, os, shutil, stat
import time, datetime
from engine import Widgets
from lib import filesmime as mimetypes
from abcommon import *
import TreeViewNew, NoteBook
from PopupMenuNew import *
from  lib.GNOMEConf import GtkConfig

conf = GtkConfig()

class treeView(Widgets):
    def __init__(self):
        Widgets.__init__(self) 
        self.__mimetype = (os.path.isfile('/usr/bin/gnome-session') \
                       and mimetypes.Gnome()) \
                       or mimetypes.notGnome(24)
        self.localtree = TreeViewNew.genericListView({
            "headers-visible"  : True,
            "headers-clickable": True,
            "rows-search"      : True,
            "rows-same-height" : False,
            "rows-alternate"   : True,
            "rows-reorder"     : False,
        })
        self._setupCulumn()
        self._addToNotebook()
   
    def _setupCulumn(self):
        self.localtree.addTextColumn("File Type", str, False, False)
        self.localtree.addImageColumn("Filename", True, True)
        self.localtree.addTextColumn("-", str, False, True, None, False, self.rename)
        self.localtree.addTextColumn("Size", str, True, False, 50)
        self.localtree.addTextColumn("Last Edit", str, True, True)
        self.localtree.mergeColumns(1, 2, None, None)
        
    def _addToNotebook(self):
        self.localBox = self.XMLtree.getWidget("LocalBox")
        localbook = NoteBook.genericNoteBook({
            "show-border"  : False,
            "show-tabs"    : True,
            "show-arrows"  : True,
            "tabs-reorder" : True,
            "group-name"   : "connection",
            "tabs-detach"  : True,
            "tabs-position": "top",
        })
        localbook.addPage(gtk.STOCK_DIRECTORY, "Filesystem Locale", self.localtree.widget, None, True)
        self.localBox.pack_start(localbook.widget, padding = 5)
        
    def listFiles(self, defaultPath = ".", showHidden = 0):
        try:
            files = {
                "local": os.listdir(defaultPath),
                "tree" : [("directory", self.__mimetype.return_folder_mime(), ".." , "4096", "")]
            }
        except: return None
            
        for item in files["local"]:
            if showHidden == 0 and item[0] == ".": continue
            try: stats = os.stat(os.path.join(".", item))
            except: continue
                
            file = {
                "type": os.path.isdir(item) and "directory" or "file", 
                "mime": os.path.isdir(item) \
                        and self.__mimetype.return_folder_mime() \
                        or self.__mimetype.return_mime(item), 
                "name": item,
                "size": str(stats.st_size),
                "edit": str(datetime.datetime.fromtimestamp(stats.st_mtime))
            }    
            files["tree"].append((
                file["type"], file["mime"], file["name"], file["size"], file["edit"]))
        files["tree"].sort()
        
        return files["tree"]
            
    def loadRows(self, *args):
        self.localtree.clearRows()
        for file in self.listFiles():
            self.localtree.addRow([
                file[0], file[1], file[2], file[3], file[4] ])
            
        
    def pwd(self):
        return os.getcwd()
    
    def cwd(self, name):
        if name == "~":
            name = os.path.expanduser("~%s" % os.environ['USER'])
        os.chdir(name)
        
    def delete(self, name):
        os.remove(name)
        
    def rmdir(self, name):
        shutil.rmtree(name)
        
    def mkdir(self, name):
        os.mkdir(name)
        self.loadRows()
    def rename(self):
        model, iter = self.localtree.widget.get_selection().get_selected()
        if iter is not None:
            d = gtk.Dialog("ff", None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_OK, gtk.RESPONSE_OK,
                           gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT))
            e = gtk.Entry()
            d.vbox.pack_start(e, True, True, 0)
            d.show_all()
            risp = d.run()
            if risp == gtk.RESPONSE_OK:
                print e.get_text()
            d.destroy()
        
class treeViewPath(Widgets):

    def __init__(self):
        Widgets.__init__(self)
        
        self.combobox = self.XMLtree.getWidget("LocalPathText")
        
    def updatePath(self, path):
        self.combobox.set_text(path)
        
    def getPath(self): 
        return self.combobox.get_text()
    
#class treeViewEvents(treeViewEngine):
    
    #def __init__(self):
        #treeViewEngine.__init__(self)
        #print Invoker(treeViewEngine, self)
        
        #self._treeViewPath = treeViewPath()    

class UI(treeView):
    
    def __init__(self):
        treeView.__init__(self)
        self.treeViewPath = treeViewPath()
        self.treeViewPath.updatePath(self.pwd())

        self.loadRows()
        self.connectEvents()
        self._setupPopup()
        
    def onPathChange(self, *args):
        self.cwd(self.treeViewPath.getPath())
        self.clearRows()
        self.loadRows()
        
        LogView = Invoker(Widgets.selectWidget("LogView").UI)
        LogView.write("Directory corrente: %s" % self.pwd())
        
    def onRowClick(self, *args):
        model, iter = self.localtree.widget.get_selection().get_selected()
        file = {
            "type": model.get_value(iter, 0),
            "name": model.get_value(iter, 2)
        }
        
        if file["type"] == "directory":
            self.cwd(os.path.join(self.pwd(), file["name"]))
            self.loadRows()
            self.treeViewPath.updatePath(self.pwd())
        else:
            try:
                open = os.system("xdg-open " + file["name"])
            except Exception, e:
                print e

        LogView = Invoker(Widgets.selectWidget("LogView").UI)
        LogView.write("Directory corrente: %s" % self.pwd())

    def connectEvents(self):
        self.localtree.widget.connect("row-activated", self.onRowClick)
#        self.XMLtree.connectSignals({
#            "on_LocalTree_row_clicked" : self.onRowClick,
#            "on_LocalPathText_activate": self.onPathChange,
#        })
    def _setupPopup(self):
        self.menu = [genericPopupMenu(), genericPopupMenu()]
        self.menu[0].addSimpleEntry("Crea cartella", "Crea nuova cartella", gtk.STOCK_NEW, "<control>N", "N", self.makeDir)
        self.menu[0].addSimpleEntry("Apri", "Apri file esistente", gtk.STOCK_OPEN, "<control>O", "O")
        self.menu[0].addSimpleEntry("Salva", "Salva file", gtk.STOCK_SAVE, "<control>S", "S", self.rename)
        self.menu[0].addSeparatorEntry()
        self.menu[0].addSimpleEntry("Esci", "Rimuovi file", gtk.STOCK_QUIT, "<control>Q", "Q")


        self.menu[1].addSimpleEntry("Homepage", "Apri da homepage", gtk.STOCK_HOME, "<control>H", "H")
        self.menu[1].addSimpleEntry("Network", "Apri da network", gtk.STOCK_NETWORK, "<control>R", "r")
        self.menu[1].addSimpleEntry("Preferenze", "Apri da preferenze", gtk.STOCK_PREFERENCES, "<control>P", "P")
        self.menu[1].addSimpleEntry("Altro", "", None, None, None)
        self.menu[1].addSeparatorEntry()
        self.menu[1].addCheckEntry("Mostra files nascosti", "Mostra i files nascosti", "<Alt>f", "f", prova, True)
        self.menu[1].addSeparatorEntry()
        self.menu[1].addRadioEntry("Visualizza per nome", "Visualizza i file per nome", "<Alt>m", "m", "radio", None, True)
        self.menu[1].addRadioEntry("Visualizza per ultima modifica", "Visualizza i file per ultima modifica", "<Alt>u", "u", "radio")
        self.menu[1].addRadioEntry("Visualizza per dimensioni", "Visualizza i file per dimensioni", "<Alt>d", "d", "radio", prova)
        
        self.menu[0].items[1].item.set_submenu(self.menu[1].widget)
        self.menu[0].linkTo(self.localtree.widget, self.popupHandler)

    def popupHandler(self, widget, event):
        if event.type == gtk.gdk.BUTTON_PRESS and event.button == 3:
            x = int(event.x)
            y = int(event.y)
            pthinfo = self.localtree.widget.get_path_at_pos(x, y)
            if pthinfo is not None:
                path, col, cellx, celly = pthinfo
                self.localtree.widget.grab_focus()
                self.localtree.widget.set_cursor(path, col, 0)
                model, iter = self.localtree.widget.get_selection().get_selected()
                file = {
                    "type": model.get_value(iter, 0),
                    "name": model.get_value(iter, 2)
                }
                if file["type"] == "directory":
                     widget.popup(None, None, None, event.button, event.time)
                else:
                    self.menu[1].widget.popup(None, None, None, event.button, event.time)
            return 1
    def makeDir(self):
            label = gtk.Label("Inserire il nome della cartella:")
            d = gtk.Dialog("Crea nuova cartella", None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_OK, gtk.RESPONSE_OK,
                           gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT))
            d.set_default_size(200, 90)
            e = gtk.Entry()
            d.vbox.pack_start(label, True, True, 0)
            d.vbox.pack_start(e, True, True, 0)
            d.show_all()
            risp = d.run()
            if risp == gtk.RESPONSE_OK:
                self.makeDir(e.get_text())
            d.destroy()